<?php

namespace App\Http\Controllers\Wechat;

use App\Models\Shop\Good;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Shop\Tag;

class GoodController extends Controller
{
    public function __construct()
    {
        view()->share([
            '_tag' => 'on'
        ]);
    }

    /***
     * 商品列表页
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index(Request $request)
    {
        $where = function ($query) use ($request) {
            if ($request->has('tag_id') and $request->tag_id != '') {
                $tag_id = $request->tag_id;
                $product_ids = \DB::table('good_tag')->where('tag_id', $tag_id)->pluck('good_id');
                $query->whereIn('id', $product_ids);
            }
        };
        $goods = Good::where($where)->orderBy('is_onsale', 1)->orderBy('created_at')->get();
        return view('wechat.goods.index', compact('goods'));
    }

    /***
     * 所有分类
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function tag()
    {
        $tags = Tag::all_tags();
        return view('wechat.goods.tag', compact('tags'));
    }


    /***
     * 商品详情页
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function show($id)
    {
        $good = Good::find($id);
        $recommends = Good::where('is_recommend', true)->where('id', '<>', $id)
            ->orderBy('is_top', 'desc')->get();
        return view('wechat.goods.show', compact('good', 'recommends'));
    }


    /***
     * 搜索
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function search()
    {
        $goods = Good::where('is_recommend', true)
            ->orderBy('is_top', "desc")
            ->orderBy('created_at')
            ->get();
        return view('wechat.goods.search', compact('goods'));
    }
}
